var express = require('express');
var router = express.Router();
const path = require('path')
const fs = require('fs')
const childProcess = require('child_process')

const versionDir = path.join(__dirname, '../version')
const initVersion = '1.0.0.0'

/* GET home page. */
router.get('/', function(req, res, next) {
  // res.render('index', { title: 'Express' });
  // console.log(versionDir, 'versionDir');
  
  const name = req.query.name
  // 确认要更新的版本号，每一个应用独立一个文件管理版本
  // 创建一个文件，默认的版本号

  // 创建一个当前应用的路径
  const currentUrl = path.join(versionDir, name)
  let newVersion = ''
  try {
    const originVersion = fs.readFileSync(currentUrl).toString().replace(/\n/g, '')
    newVersion = originVersion.replace(/\.(\d+)$/, (a, b) => `.${+b + 1}`)
    fs.writeFileSync(currentUrl, newVersion)
  } catch (error) {
    fs.writeFileSync(currentUrl, initVersion)
  }
  // 构建 打包 发布
  const originPath = path.join(__dirname, '../../../', name)
  const originDist = path.join(originPath, 'dist')
  const bagPath = path.join(__dirname, '../bag')
  // 通过运行打包命令来创建对应的打包产物
  try {
    // 1、先构建打包
    childProcess.execSync(`cd ${originPath} && npm i && npm run build`)
    // 2、在server中创建最新版本目录
    childProcess.execSync(`cd ${bagPath} && mkdir -p ./${name}/${newVersion}`)
    // 3、将打包好的包放进server目录中
    const lastDist = path.jpin(bahPath, `./${name}/${newVersion}`)
    childProcess.execSync(`mv ${originDist}/* ${lastDist}`)
  } catch (e) {
    console.log(e);
  }
  
  console.log(originDist, '构建 打包 发布');
  
  res.send('this is express server')
});

module.exports = router;
